// user.controller.ts
import {
  Controller,
  Post,
  Body,
  Get,
  Param,
  BadRequestException,
  Put,
  Request,
  UseGuards,
  Logger,
} from '@nestjs/common';
import { UserService } from './users.service';
import { AuthGuard } from '@nestjs/passport';

@Controller('users')
export class UserController {
  private readonly logger = new Logger(UserController.name);

  constructor(private readonly userService: UserService) {}

  // 注册用户
  @Post('register')
  async register(
    @Body() userData: { phone: string; password: string; name: string },
  ) {
    try {
      this.logger.log(`开始注册用户，手机号: ${userData.phone}`);
      const result = await this.userService.createUser(
        userData.phone,
        userData.password,
        userData.name,
      );
      this.logger.log(`用户注册成功，用户ID: ${result.id}`);
      return {
        success: true,
        data: result,
        message: '注册成功',
      };
    } catch (error: any) {
      this.logger.error(`注册失败: ${error.message}`, error.stack);
      return {
        success: false,
        data: null,
        message: '注册失败: ' + error.message,
      };
    }
  }

  // 获取当前用户资料
  @UseGuards(AuthGuard('jwt'))
  @Get('me')
  async getCurrentUser(@Request() req) {
    // 从JWT token中获取用户信息，req.user是完整的用户对象
    this.logger.log('获取当前用户信息，req.user:', req.user);
    return {
      success: true,
      data: req.user,
      message: '获取用户信息成功',
    };
  }

  // 获取当前用户资料
  @UseGuards(AuthGuard('jwt'))
  @Get('profile')
  async getCurrentUserProfile(@Request() req) {
    try {
      // 从JWT token中获取用户信息，req.user是完整的用户对象
      this.logger.log('获取当前用户资料，req.user:', req.user);
      // req.user 已经是完整的用户对象，不需要再查询
      if (!req.user) {
        this.logger.log(`用户不存在`);
        return {
          success: false,
          data: null,
          message: '用户不存在',
        };
      }
      this.logger.log(`获取用户资料成功，用户ID: ${req.user.id}`);
      return {
        success: true,
        data: req.user,
        message: '获取用户资料成功',
      };
    } catch (error: any) {
      this.logger.error(`获取用户资料失败: ${error.message}`, error.stack);
      return {
        success: false,
        data: null,
        message: '获取用户资料失败: ' + error.message,
      };
    }
  }

  // 更新用户个人资料
  @UseGuards(AuthGuard('jwt'))
  @Put('profile')
  async updateUserProfile(@Request() req, @Body() profileData: Partial<any>) {
    try {
      const userId = parseInt(req.user.id);
      this.logger.log(`更新用户个人资料，用户ID: ${userId}`);
      const result = await this.userService.updateUserProfile(
        userId,
        profileData,
      );
      if (!result) {
        this.logger.log(`用户不存在，用户ID: ${userId}`);
        return {
          success: false,
          data: null,
          message: '用户不存在',
        };
      }
      this.logger.log(`更新个人资料成功，用户ID: ${userId}`);
      return {
        success: true,
        data: result,
        message: '更新个人资料成功',
      };
    } catch (error: any) {
      this.logger.error(`更新个人资料失败: ${error.message}`, error.stack);
      return {
        success: false,
        data: null,
        message: '更新个人资料失败: ' + error.message,
      };
    }
  }

  // 更新用户位置信息
  @UseGuards(AuthGuard('jwt'))
  @Put('location')
  async updateUserLocation(
    @Request() req,
    @Body()
    locationData: {
      latitude: number;
      longitude: number;
      location: string;
      locationDetails?: {
        country?: string;
        province?: string;
        city?: string;
        district?: string;
        source?: 'amap' | 'google'; // 标记位置信息来源
      };
    },
  ) {
    try {
      const userId = parseInt(req.user.id);
      this.logger.log(`更新用户位置信息，用户ID: ${userId}`);
      const result = await this.userService.updateUserLocation(
        userId,
        locationData.latitude,
        locationData.longitude,
        locationData.location,
        locationData.locationDetails,
      );
      this.logger.log(`更新位置信息成功，用户ID: ${userId}`);
      return {
        success: true,
        data: result,
        message: '更新位置信息成功',
      };
    } catch (error: any) {
      this.logger.error(`更新位置信息失败: ${error.message}`, error.stack);
      return {
        success: false,
        data: null,
        message: '更新位置信息失败: ' + error.message,
      };
    }
  }

  // 根据国籍获取用户
  @UseGuards(AuthGuard('jwt'))
  @Get('by-nationality/:nationality')
  async getUsersByNationality(@Param('nationality') nationality: string) {
    try {
      this.logger.log(`根据国籍获取用户，国籍: ${nationality}`);
      const result = await this.userService.findUsersByNationality(nationality);
      this.logger.log(`获取用户成功，国籍: ${nationality}`);
      return {
        success: true,
        data: result,
        message: '获取用户成功',
      };
    } catch (error: any) {
      this.logger.error(`获取用户失败: ${error.message}`, error.stack);
      return {
        success: false,
        data: [],
        message: '获取用户失败: ' + error.message,
      };
    }
  }

  // 获取点赞列表（谁赞了我）
  @UseGuards(AuthGuard('jwt'))
  @Get('likes')
  async getLikes(@Request() req) {
    try {
      const userId = parseInt(req.user.id);
      this.logger.log(`获取点赞列表，用户ID: ${userId}`);
      return {
        success: false,
        data: [],
        message: '该功能尚未实现',
      };
    } catch (error: any) {
      this.logger.error(`获取点赞列表失败: ${error.message}`, error.stack);
      return {
        success: false,
        data: [],
        message: '获取点赞列表失败: ' + error.message,
      };
    }
  }

  // 获取访客列表（谁访问了我的主页）
  @UseGuards(AuthGuard('jwt'))
  @Get('visitors')
  async getVisitors(@Request() req) {
    try {
      const userId = parseInt(req.user.id);
      this.logger.log(`获取访客列表，用户ID: ${userId}`);
      return {
        success: false,
        data: [],
        message: '该功能尚未实现',
      };
    } catch (error: any) {
      this.logger.error(`获取访客列表失败: ${error.message}`, error.stack);
      return {
        success: false,
        data: [],
        message: '获取访客列表失败: ' + error.message,
      };
    }
  }

  // 获取用户统计数据
  @UseGuards(AuthGuard('jwt'))
  @Get('stats')
  async getUserStats(@Request() req) {
    try {
      const userId = parseInt(req.user.id);
      this.logger.log(`获取用户统计数据，用户ID: ${userId}`);

      // 获取用户统计数据的实现
      const userData =
        await this.userService.findUserWithoutPasswordById(userId);
      if (!userData) {
        return {
          success: false,
          data: null,
          message: '用户不存在',
        };
      }

      // 返回统计数据（移除了nearby字段）
      const stats = {
        likedBy: Math.floor(Math.random() * 100), // 示例数据
        liked: Math.floor(Math.random() * 100), // 示例数据
        visitors: Math.floor(Math.random() * 100), // 示例数据
        newVisitors: Math.floor(Math.random() * 10), // 示例数据
      };

      return {
        success: true,
        data: stats,
        message: '获取用户统计数据成功',
      };
    } catch (error: any) {
      this.logger.error(`获取用户统计数据失败: ${error.message}`, error.stack);
      return {
        success: false,
        data: null,
        message: '获取用户统计数据失败: ' + error.message,
      };
    }
  }

  // 获取用户资料
  @Get(':id')
  async getUserInfo(@Param('id') id: string) {
    // 在控制器层面也增加ID验证
    if (!id || id === 'register') {
      throw new BadRequestException('Invalid user ID');
    }

    try {
      const userId = parseInt(id);
      this.logger.log(`获取用户信息，用户ID: ${userId}`);
      const result = await this.userService.findUserWithoutPasswordById(userId);
      if (!result) {
        this.logger.log(`用户不存在，用户ID: ${userId}`);
        return {
          success: false,
          data: null,
          message: '用户不存在',
        };
      }
      this.logger.log(`获取用户信息成功，用户ID: ${userId}`);
      return {
        success: true,
        data: result,
        message: '获取用户信息成功',
      };
    } catch (error: any) {
      this.logger.error(`获取用户信息失败: ${error.message}`, error.stack);
      return {
        success: false,
        data: null,
        message: '获取用户信息失败: ' + error.message,
      };
    }
  }
}
